<template>

  <!-- 子抽屉 -->
  <a-modal :title="titleMap" :visible="childrenDrawer" @ok="createAction " @cancel="onChildrenDrawerClose" :width="680"
           :ok-text="$t('user.verification-code.required1166')" :cancel-text="$t('user.email.required11')"
           :ok-button-props="{ disabled: true }">
    <template v-slot:footer>
      <a-button @click="createAction" type="primary">{{ $t('user.verification-code.required1166') }}</a-button>
      <a-button @click="onChildrenDrawerClose">{{ $t('user.email.required11') }}</a-button>
    </template>
    <a-form :form="form" labelAlign="right">
      <!-- 这个部分是隐藏的数据 -->
      <a-form-item label="ID" class="hidden">
        <a-input v-decorator="['Id']"/>
      </a-form-item>
      <a-form-item style="margin: 0;" label="合规要求编号:">
        <a-input v-decorator="['DpiaActionIdTag']" style="width: 615px;" disabled/>
      </a-form-item>
      <a-form-item style="margin: 0;" :label="$t('user.verification-code.required111566172')">
        <a-input
            v-decorator="['DpiaActionName', { rules: [{ required: true, message: $t('user.verification-code.required111566110577324') }] }]"
            :placeholder="$t('user.verification-code.required111566172')" style="width: 615px;" :disabled="disabled2"/>
      </a-form-item>
      <a-form-item style="margin: 0;" :label="$t('user.verification-code.required111566173')">
        <a-textarea :auto-size="{ minRows: 3, maxRows: 10 }"
                    :placeholder="$t('user.verification-code.required11156617311')" :rows="3"
                    v-decorator="['DpiaActionInfo', { rules: [{ required: true, message: $t('user.verification-code.required111566110577281') }] }]"
                    style="width: 615px;" :disabled="disabled2"/>
      </a-form-item>

      <a-row>
        <!-- 对象组合 -->
        <a-col :span="12">
          <a-form-item :label="$t('user.verification-code.required111566174')">
            <a-select
                v-decorator="['DpiaActionUserId', { rules: [{ required: true, message: $t('user.verification-code.required11156611057737144228143122244') }] }]"
                :placeholder="$t('user.verification-code.required111566175')" show-search option-filter-prop="children"
                :default-active-first-option="false" v-model="inputValue" @search="filterOption" :showArrow="false" allowClear
                 style="width: 300px" :disabled="disabled2">
              <a-select-option v-for="item in userList" :value="item.value" :key="item.value">
                {{ item.label }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item :label="$t('user.login.message-invalid-verification-code0011')">
            <a-select v-decorator="['DpiaActionStatus', { rules: [{ required: true, message: $t('user.v157') }] }]"
                      :placeholder="$t('user.login.message-invalid-verification-code0011')" style="width: 300px;">
              <a-select-option v-for="item in statusList" :value="item.value" :key="item.value">
                {{ $t(item.label) }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
      </a-row>

      <!-- 备注的timeline -->
      <a-form-item label="法律法规详细来源">
        <a-timeline>
          <a-timeline-item v-for="(item, index) in inputList" :key="item.index">
            <!-- 操作按钮 -->
            <a-space size="0" align="center">
              <p style="min-width: 150px;">{{ item.actionCreateUser }} {{ item.actionCreateTime }}</p>
              <a-button v-if="item.editable === false" type="link" @click="editInput(item, index)">{{
                  $t('user.verification-code.required111566147')
                }}
              </a-button>
              <a-button v-if="item.editable === true && !disabled2" type="link" @click="okInput(item, index)">{{
                  $t('user.verification-code.required1166')
                }}
              </a-button>
              <a-button type="link" @click="deleteInput(item)" v-if="!disabled2">{{ $t('app.setting.copy') }}</a-button>
            </a-space>
            <a-form-item>
              <a-textarea :auto-size="{ minRows: 3, maxRows: 10 }"
                          :placeholder="$t('user.verification-code.required111566182')" :rows="3"
                          :disabled="!item.editable"
                          v-model="item.value"/>
            </a-form-item>
          </a-timeline-item>
          <!-- 备注的新增 -->
          <a-button style="float: right;" @click="addInput" :disabled="disabled2">{{
              $t('user.verification-code.required1115661106')
            }}
          </a-button>
        </a-timeline>
      </a-form-item>
      <!-- 文件上传 -->
      <a-upload name="file" :remove="delFile" :file-list="fileLists" :multiple="true" :customRequest="handleChange"
                :disabled="disabled2">
        <a-button>
          <a-icon type="upload"/>
          落地要求示例和验收标准示例
        </a-button>
      </a-upload>
    </a-form>
  </a-modal>
</template>

<script>
import {getUserList} from '@/api/common/form'
import moment from 'moment'
import {dpiaRemarkLists, ristCreateAction, ristDelActionRemark} from '@/api/risk/form'
import axios from 'axios'
import {FilesDel, rickActiondel} from '@/api/dpia/form'
import {ristCreateActionRemark, ristEditActionRemark} from '@/api/risk/json'
import storage from "store";
import {ACCESS_TOKEN} from "@/store/mutation-types";

export default {
  created() {
    this.init()
  },
  props: {
    mode: {
      type: String
    },
    riskId: {
      type: Number
    },
    editId: {
      type: Number
    },
    state: {
      type: Number
    }
  },
  data() {
    return {
      keyword: '',
      childrenDrawer: false,
      // titleMap: ['新增措施', '修改措施'],
      titleMap: '',
      form: this.$form.createForm(this),
      // 时间配置
      config: {
        rules: [{type: 'object', required: true, message: this.$t('user.verification-code.required111566110577285')}],
      },
      env: process.env.VUE_APP_BASE_API,
      headers: {
        authorization: 'authorization-text',
      },

      selectList: [
        {
          value: '1',
          label: 'Draft'
        },
        {
          value: '2',
          label: 'Submitted'
        },
        {
          value: '3',
          label: 'In-progress'
        },
        {
          value: '4',
          label: 'Completed'
        },
        {
          value: '5',
          label: 'To be edited'
        }
      ],
      // 状态下拉
      statusList: [
        {
          'label': 'user.verification-code.required111566133',
          'value': 1
        },
        {
          'label': 'user.verification-code.required1115661455555',
          'value': 3
        },
        {
          'label': 'user.verification-code.required111566146',
          'value': 4
        },
        {
          'label': 'user.verification-code.required111566110577371442281431222335566555555',
          'value': 5
        },
      ],
      userList: [],
      inputList: [],
      fileLists: [],
      edit: '',
      //点击新建空模板Id
      actionId: '',
      remark: {},
      okType: '',
      urlList: [],
      disabled2: false,
      actionType: '',
      // 备注用的信息
      actionCreateUser: this.$store.state.user.info.name,
      actionCreateUserId: "",
      timerId: '',
      inputValue: undefined,
      ifDel: false
    }
  },
  watch: {
    async inputValue(value) {
        const {data} = await getUserList({UserEmail: value, UserName: value})
        this.userList = data
    }
  },
  methods: {
    disabledDate(current) {
      const currentDate = moment().format('YYYY-MM-DD');
      return current && current.format('YYYY-MM-DD') < currentDate;
    },
    // 用户查询
    async filterOption(value) {
      this.inputValue = value
      // if (event.key === 'Enter'|| event.keyCode === 13){
      //   const value = event.target.value;
      //   const { data } = await getUserList({ UserEmail: value,UserName:value })
      //   this.userList = data
      //   console.log("search:", this.userList)
      // }

    },
    //删除上传文件
    async delFile(file) {
      console.log('1');
      console.log('file', file);
      const index = this.fileLists.indexOf(file);
      this.fileLists.splice(index, 1);
      await FilesDel({Id: file.fileId})
      return true;
    },
    async init() {
      this.listLoading = true
      try {

        // 获取用户列表下拉
        // const { data: userList } = await userQuery(1);
        // this.userList = userList
      } catch (error) {
        // 报错信息
        this.$message.error(error)
      } finally {
        // 不管成功失败都会执行
        this.listLoading = false
      }
    },
    disabledDate(current) {
      const currentDate = moment().format('YYYY-MM-DD');
      return current && current.format('YYYY-MM-DD') < currentDate;
    },
    //子抽屉展示 state = 2为审阅编辑
    async openAction(editId, data, state, ifDel) {
      this.userList = []
      this.ifDel = ifDel
      if (state == '0') {
        this.titleMap = this.$t('user.verification-code.required111566164')
      } else {
        this.titleMap = this.$t('user.verification-code.required11156616411')
      }
      if (state == 2) {
        this.disabled2 = true
      } else {
        this.disabled2 = false
      }
      this.childrenDrawer = true;
      this.inputList = []
      this.fileLists = []
      if (!data) {
        this.actionType = '0'
        await this.$nextTick()
        this.form.setFieldsValue({
          DpiaActionIdTag: data.DpiaActionIdTag,
          Id: data.Id
        })
        // 保留创建时间、创建人信息
        this.actionCreateUser = data.DpiaActionCreateUser;

        if (data.DpiaActionUserId == 0) {
          this.form.setFieldsValue({DpiaActionUserId: undefined})
        } else {
          this.form.setFieldsValue({DpiaActionUserId: data.DpiaActionUserId})
        }
        this.addInput()
      } else {
        let DpiaActionStatusName = ''
        this.statusList.forEach(
            (item) => {
              if (item.value == data.DpiaActionStatus) {
                DpiaActionStatusName = this.$t(item.label)
              }
            }
        )
        this.userList.push({
          value: data.DpiaActionUserId,
          label: data.DpiaActionUserResponsible
        })
        this.actionId = data.Id
        this.actionType = '1'
        // this.titleMap = this.$t('user.verification-code.required11156616411')
        await this.$nextTick()
        this.form.setFieldsValue({
          DpiaActionIdTag: data.DpiaActionIdTag,
          DpiaActionName: data.DpiaActionName,
          DpiaActionInfo: data.DpiaActionInfo,
          DpiaActionStatus: DpiaActionStatusName,
          // DpiaActionFinishTime: moment(data.DpiaActionFinishTime, 'YYYY-MM-DD'),
          DpiaActionUserId: data.DpiaActionUserId,
          DpiaActionDcoId: data.DpiaActionDcoId,
          DpiaActionResult: data.DpiaActionResult
        })
        if (data.DpiaActionUserId == 0) {
          this.form.setFieldsValue({DpiaActionUserId: undefined})
        } else {
          this.form.setFieldsValue({DpiaActionUserId: data.DpiaActionUserId})
        }
        const {data: remarkLists} = await dpiaRemarkLists({ActionId: this.actionId, ActionType: 1})
        // 保留创建时间、创建人信息
        this.actionCreateUser = data.DpiaActionCreateUser;
        this.actionCreateUserId = data.DpiaActionCreateUserId;
        if (remarkLists.length > 0) {
          for (var i = 0; i < remarkLists.length; i++) {
            // 创建备注列表初始化
            this.inputList.push({
              Id: remarkLists[i].Id,
              value: remarkLists[i].ActionRemarkInfo,
              editable: false,
              actionCreateTime: remarkLists[i].ActionCreatetime,
              actionCreateUser: remarkLists[i].ActionCreateUserName,
              actionCreateUserId: remarkLists[i].ActionCreateUser,
            });
          }
        }
        this.addInput();
        const {data: fileLists} = await dpiaRemarkLists({ActionId: this.actionId, ActionType: 2})
        if (fileLists.length > 0) {
          for (var i = 0; i < fileLists.length; i++) {
            // 上传的文件处理
            var fileName = fileLists[i].ActionUploadUrl.split("/")
            this.fileLists.push({
              uid: i,
              name: fileName[fileName.length - 1],
              status: "done",
              url: fileLists[i].ActionUploadUrl,
              fileId: fileLists[i].Id
            })
          }
        }
      }
    },

    //子抽屉关闭
    async onChildrenDrawerClose(type) {
      if (this.mode == 0) {
        // this.titleMap=this.$t('user.verification-code.required111566164')
        this.$emit('getList', this.riskId)
      } else {
        // this.titleMap=this.$t('user.verification-code.required11156616411')
        this.$emit('getList', this.editId)
      }
      if(this.ifDel && type !== 0) {
        await rickActiondel({Id: this.actionId})
      }
      this.actionId = null
      this.childrenDrawer = false;
      // 清空form的值
      this.form.resetFields()
    },
    //新建action
    async createAction() {
      // 提交创建题目
      const {
        form: {validateFields},
      } = this
      // 按钮loading
      this.loading = true
      validateFields({force: true}, async (err, values) => {
        // const RiskStartTime = moment(values['DpiaActionFinishTime']).format('YYYY-MM-DD')
        // values["DpiaActionFinishTime"] = RiskStartTime
        if (this.mode == '0') {
          values["RiskId"] = this.riskId
        } else {
          values["RiskId"] = this.editId
        }
        if (!err) {
          for (var arr = 0; arr < this.userList.length; arr++) {
            if (this.userList[arr].value == values.DpiaActionUserId) {
              values.DpiaActionUserResponsible = this.userList[arr].label
            }
          }
          for (var arr = 0; arr < this.userList.length; arr++) {
            if (this.userList[arr].value == values.DpiaActionDcoId) {
              values.DpiaActionDcoReview = this.userList[arr].label
            }
          }
          try {
            values["Id"] = this.actionId
            values.DpiaActionUserId = values.DpiaActionUserId.replaceAll('/', '#@%$')
            const {data} = await ristCreateAction(values)
            this.$message.success(this.$t('user.verification-code.required111566171'))
            this.onChildrenDrawerClose(0)
          } catch (error) {
            this.$message.error(error)
          } finally {
            this.loading = false
          }
          this.modalVisible = false;
          this.form.resetFields()
          this.$emit("finishList")
        } else {
          setTimeout(() => {
            this.loading = false
          }, 600)
        }
      })
    },
    //文件上传
    async handleChange(e) {
      // 上传提交
      this.uploadLoading = true
      let formdata = new FormData()
      formdata.append('file', e.file)
      try {
        const {status, data} = await axios({
          url: `${this.env}/v1/oss/upload`,
          method: 'post',
          data: formdata,
          headers: {
            token: storage.get(ACCESS_TOKEN),
            tokens: storage.get("bmwToken") || "",
          },
        })
        if (status == 200 && data.code == 1) {
          if (data.data != "") {
            await this.$nextTick()
            var files = data.data;
            var index = this.fileLists.length;
            if (files != "" && files != undefined) {
              var fileName = files.split("/")
              // 上传文件完成后新增
              // 新增
              const fileId = await ristCreateActionRemark([{
                ActionUploadUrl: data.data, ActionId: this.actionId, ActionType: 2
              }])
              this.fileLists.push({
                uid: index + 1,
                name: fileName[fileName.length - 1],
                status: "done",
                url: data.Url + data.data,
                fileId: fileId.data.Id
              })
            }
          }
        } else {
          this.$message.error(this.$t('user.verification-code.required111566110577282'))
        }
      } catch (error) {
        console.log(error)
        this.$message.error(error)
      } finally {
        this.uploadLoading = false
      }
    },
    // 添加
    addInput() {
      var objData = new Date();
      var year = objData.getFullYear();
      var month = objData.getMonth() + 1;
      var day = objData.getDate();
      if (objData.getSeconds() < 10) {
        var seconds = '0' + objData.getSeconds();
      } else {
        var seconds = objData.getSeconds();
      }
      if (objData.getMinutes() < 10) {
        var miuntes = '0' + objData.getMinutes();
      } else {
        var miuntes = objData.getMinutes();
      }
      if (objData.getHours() < 10) {
        var hours = '0' + objData.getHours();
      } else {
        var hours = objData.getHours();
      }
      if (month < 10) {
        month = '0' + month;
      }
      if (day < 10) {
        day = '0' + day
      }
      // 新增一个新的数据初始化
      this.inputList.push({
        value: "",
        editable: true,
        actionCreateTime: year + "-" + month + "-" + day + " " + hours + ":" + miuntes + ":" + seconds,
        actionCreateUser: this.actionCreateUser,
        actionCreateUserId: this.actionCreateUserId
      });
    },
    //编辑
    async editInput(item) {
      // this.okType = '1'
      item.editable = true;
      // console.log(this.actionId);
    },
    async okInput(item, index) {
      console.log(item);
      // 修改状态为不可编辑
      item.editable = false
      console.log(Object.keys(item).indexOf("Id"));
      if (Object.keys(item).indexOf("Id") != -1) {
        // 更新
        const {data} = await ristEditActionRemark([{
          Id: item.Id, ActionRemarkInfo: item.value, ActionId: this.actionId, ActionType: 1
        }])
        item.actionCreateTime = data.ActionUpdatetime
      } else {
        console.log('新增');
        // 新增
        const {data} = await ristCreateActionRemark([{
          ActionRemarkInfo: item.value, ActionId: this.actionId, ActionType: 1
        }])
        // 赋值
        item.Id = data.Id
        item.actionCreateTime = data.ActionCreatetime
      }
    },
    //删除
    async deleteInput(item) {
      // console.log(item.id);
      // await ristDelActionRemark(item.id)
      // const index = this.inputList.indexOf(item);
      // this.inputList.splice(index, 1);
      // 删除备注
      try {
        console.log(item);
        if (Object.keys(item).indexOf("Id") != -1) {
          console.log('删除');
          // 防止ID被初始化
          if (item.Id != 0) {

            await ristDelActionRemark({Id: item.Id})
          }
        }
        // 在列表里也删除
        this.inputList.splice(this.inputList.indexOf(item), 1);
      } catch (error) {
        console.log("error:", error)
        this.$message.error(error)
      }
    },
  }


}

</script>

<style lang="less" scoped>
/deep/ .ant-timeline-item-content {
  top: -11px;
}

/deep/ .ant-timeline-item {
  padding: 0 0 1px;
}

/deep/ .ant-form-item {
  margin-bottom: 0px;
}
</style>